#!/bin/bash

# Check if required arguments are provided
if [ "$#" -lt 2 ]; then
    echo "Usage: $0 <log_file_prefix> <num_ranks> [output_file]"
    echo "Example: $0 app 4 merged_output.log"
    exit 1
fi

prefix=$1
num_ranks=$2
output_file=${3:-"merged_${prefix}.log"}

# Temporary file for processing
temp_file=$(mktemp)

# Function to check if file exists
check_file() {
    if [ ! -f "$1" ]; then
        echo "Warning: File $1 does not exist, skipping..."
        return 1
    fi
    return 0
}

# Process each rank's log file
for ((rank=0; rank<num_ranks; rank++)); do
    input_file="${prefix}_rank${rank}.log"
    
    if check_file "$input_file"; then
        # Concatenate the file to our temporary file
        cat "$input_file" >> "$temp_file"
    fi
done

# Sort the combined file based on timestamp including milliseconds
# Format: [YYYY-MM-DD HH:MM:SS.mmm] [other content...]
sort -t']' -k1,1 "$temp_file" > "$output_file"

# Clean up
rm "$temp_file"

echo "Merged log files have been written to: $output_file" 